package cn.lyh.gulimall.product.service;

import cn.lyh.gulimall.product.dao.PmsAttrAttrgroupRelationMapper;
import cn.lyh.gulimall.product.dao.PmsAttrGroupMapper;
import cn.lyh.gulimall.product.dao.PmsCategoryMapper;
import cn.lyh.gulimall.product.entity.PmsAttrAttrgroupRelation;
import cn.lyh.gulimall.product.entity.PmsAttrGroup;
import cn.lyh.gulimall.product.entity.PmsCategory;
import cn.lyh.gulimall.product.vo.AttrRelationVo;
import cn.lyh.gulimall.product.vo.AttrRespVo;
import cn.lyh.gulimall.product.vo.AttrVo;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lyh.gulimall.product.entity.PmsAttr;
import cn.lyh.gulimall.product.dao.PmsAttrMapper;
import org.springframework.transaction.annotation.Transactional;
import utils.PageUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lyh
 * @version 1.0
 * @since 2021/4/6
 */
@Service
public class PmsAttrService extends ServiceImpl<PmsAttrMapper, PmsAttr> {

	@Autowired
	PmsAttrAttrgroupRelationMapper relationMapper;

	@Autowired
	PmsAttrGroupMapper attrGroupMapper;

	@Autowired
	PmsCategoryMapper categoryMapper;

	@Autowired
	PmsCategoryService categoryService;

	@Transactional(rollbackFor = Exception.class)
	public void saveAttr(AttrVo attrVo) {
		// 时候给Attr表中保存基本信息
		PmsAttr pmsAttr = new PmsAttr();
		BeanUtils.copyProperties(attrVo, pmsAttr);
		this.save(pmsAttr);
		// 保存关联表数据
		if (attrVo.getAttrType() == 1){
			PmsAttrAttrgroupRelation pmsAttrAttrgroupRelation = new PmsAttrAttrgroupRelation();
			pmsAttrAttrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
			pmsAttrAttrgroupRelation.setAttrId(pmsAttr.getAttrId());
			relationMapper.insert(pmsAttrAttrgroupRelation);
		}
	}

	public PageUtils quertBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
		// 获取key
		String key = (String) params.get("key");
		// 构造查询条件
		QueryWrapper<PmsAttr> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq(PmsAttr.COL_ATTR_TYPE, "base".equalsIgnoreCase(attrType) ? 1 : 0);
		if (catelogId != 0) {
			queryWrapper.eq(PmsAttr.COL_CATELOG_ID, catelogId);
		}

		if (!StringUtils.isNullOrEmpty(key)) {
			queryWrapper.and((obj) -> {
				obj.eq(PmsAttr.COL_ATTR_ID, key).or().like(PmsAttr.COL_ATTR_NAME, key);
			});
		}
		// 获取分页数据
		long curPage = params.get("page") != null ? Long.parseLong((String) params.get("page")) : 1;
		long limit = params.get("limit") != null ? Long.parseLong((String) params.get("limit")) : 10;

		// Id为0无条件查询
		IPage<PmsAttr> page = this.page(new Page<>(curPage, limit), queryWrapper);
		PageUtils pageUtils = new PageUtils(page);

		List<PmsAttr> records = page.getRecords();
		List<AttrRespVo> respVos = records.stream().map((pmsAttr) -> {
			AttrRespVo attrRespVo = new AttrRespVo();
			BeanUtils.copyProperties(pmsAttr, attrRespVo);
			// 设置分类和分组的名字 判断是销售还是基本
			if ("base".equalsIgnoreCase(attrType)) {
				PmsAttrAttrgroupRelation pmsAttrAttrgroupRelation =
						relationMapper.selectOne(
								new QueryWrapper<PmsAttrAttrgroupRelation>()
										.eq(PmsAttrAttrgroupRelation.COL_ATTR_ID, pmsAttr.getAttrId())
						);
				if (pmsAttrAttrgroupRelation != null) {
					Long attrGroupId = pmsAttrAttrgroupRelation.getAttrGroupId();
					// 利用组Id查询
					PmsAttrGroup attrGroup = attrGroupMapper.selectById(attrGroupId);
					attrRespVo.setGroupName(attrGroup.getAttrGroupName());
				}
			}
			PmsCategory pmsCategory = categoryMapper.selectById(pmsAttr.getCatelogId());
			if (pmsCategory != null) {
				attrRespVo.setCatelogName(pmsCategory.getName());
			}
			return attrRespVo;
		}).collect(Collectors.toList());
		pageUtils.setList(respVos);
		return pageUtils;
	}

	public AttrRespVo getInfoByAttrId(Long attrId) {
		// 先根据id 查询得到attr对象
		PmsAttr pmsAttr = this.baseMapper.selectById(attrId);
		AttrRespVo attrRespVo = new AttrRespVo();
		BeanUtils.copyProperties(pmsAttr, attrRespVo);
		// 设置分组信息
		PmsAttrAttrgroupRelation attrgroupRelation = relationMapper.selectOne(
				new QueryWrapper<PmsAttrAttrgroupRelation>().eq(PmsAttrAttrgroupRelation.COL_ATTR_ID, pmsAttr.getAttrId()));
		if (attrgroupRelation != null) {
			attrRespVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
			PmsAttrGroup attrGroup = attrGroupMapper.selectById(attrgroupRelation.getAttrGroupId());
			if (attrGroup != null) {
				attrRespVo.setGroupName(attrGroup.getAttrGroupName());
			}
		}
		// 查询分类信息并设置
		Long catelogId = pmsAttr.getCatelogId();
		Long[] catelogPath = categoryService.findCatelogPath(catelogId);
		attrRespVo.setCatelogPath(catelogPath);

		PmsCategory category = categoryMapper.selectById(catelogId);
		if (category != null) {
			attrRespVo.setCatelogName(category.getName());
		}

		return attrRespVo;
	}

	public void updateAttr(AttrVo attrVo) {
		PmsAttr pmsAttr = new PmsAttr();
		BeanUtils.copyProperties(attrVo, pmsAttr);
		this.updateById(pmsAttr);
		PmsAttrAttrgroupRelation attrAttrgroupRelation = new PmsAttrAttrgroupRelation();
		attrAttrgroupRelation.setAttrGroupId(attrVo.getAttrGroupId());
		attrAttrgroupRelation.setAttrId(attrVo.getAttrId());
		// 修改分组关联

		Integer count = relationMapper.selectCount(new QueryWrapper<PmsAttrAttrgroupRelation>()
				.eq(PmsAttrAttrgroupRelation.COL_ATTR_ID, attrVo.getAttrId()));
		if (count > 0) {
			relationMapper.update(
					attrAttrgroupRelation,
					new UpdateWrapper<PmsAttrAttrgroupRelation>()
							.eq(PmsAttrAttrgroupRelation.COL_ATTR_ID, attrVo.getAttrId()));
		} else {
			relationMapper.insert(attrAttrgroupRelation);
		}
	}

	public void deleteRelations(AttrRelationVo[] attrRelationVos) {
		List<PmsAttrAttrgroupRelation> relationList = Arrays.asList(attrRelationVos).stream().map(attrRelationVo -> {
			PmsAttrAttrgroupRelation relation = new PmsAttrAttrgroupRelation();
			BeanUtils.copyProperties(attrRelationVo, relation);
			return relation;
		}).collect(Collectors.toList());

		relationMapper.deleteBatchRelation(relationList);
	}
}
